package com.kinon.tyjaccount.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.kinon.tyjaccount.Constatus;
import com.kinon.tyjaccount.R;
import com.kinon.tyjaccount.adapter.UrgentWucanAdapter;
import com.kinon.tyjaccount.adapter.WucanAdapter;
import com.kinon.tyjaccount.data.DataModel;
import com.kinon.tyjaccount.data.UPacketFactory;
import com.kinon.tyjaccount.entity.ItemBean;
import com.kinon.tyjaccount.entity.KVP;
import com.kinon.tyjaccount.entity.WucanEntity;
import com.kinon.tyjaccount.sqlitebean.Card;
import com.kinon.tyjaccount.sqlitebean.SettletmentBean;
import com.kinon.tyjaccount.tools.HttpTools;
import com.kinon.tyjaccount.tools.NetWorkUtil;
import com.kinon.tyjaccount.tools.SharedPreferencesUtil;
import com.kinon.tyjaccount.tools.SysTimeManage;
import com.kinon.tyjaccount.tools.ToastUtil;
import com.kinon.tyjaccount.tools.Utility;
import com.kinon.tyjaccount.uitl.SoundPoolManage;
import com.kinon.tyjaccount.view.JiesuanjineActivity;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import sunmi.ds.DSKernel;
import sunmi.ds.callback.ICheckFileCallback;
import sunmi.ds.callback.ISendCallback;
import sunmi.ds.data.DataPacket;

import static com.kinon.tyjaccount.view.MainActivity.amount;
import static com.kinon.tyjaccount.view.MainActivity.infolist;
import static com.kinon.tyjaccount.view.MainActivity.pathBig;
import static org.litepal.crud.DataSupport.where;

/**午餐*/

public class WucanFragment extends Fragment implements View.OnClickListener{
	
	/** 刷新 */
	private ListView lv;
	
	int offset = 0;
	int page = 8;
	String token = "";
	EditText et_id;
//	private static int amount=0;
	TextView tv_amount;
	private Button btn_clearCard;
	/**获得数据*/

	HttpTools httptools=null;
	WucanAdapter wucanAdapter;
	ToastUtil toastUtil=new ToastUtil();

	//副屏显示的菜品列表
	List<ItemBean> items ;
	//副屏的取餐编号和共计
	List<KVP> sm ;
	// SDK核心类
	DSKernel mDSKernel ;
	 private String packageName= DSKernel.getDSDPackageName();
	private static final String WELCOME_IMG_ID = "WELCOME_IMG_ID";
	long taskId;

	Handler showHandle=new Handler();

	//紧急情况下使用的数据
	private ArrayList<SettletmentBean> selist;
	private UrgentWucanAdapter uWAdapter=null;
	private static int lunchNum=0;

	private String on_card="";
	private  long nonce_time;

	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_wucan, null);
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		initRes();
	}
	private void initRes() {
		SharedPreferences sp = getActivity().getSharedPreferences("spReg",
				Context.MODE_PRIVATE);
		token = sp.getString("data", "");
		lv=(ListView)getView().findViewById(R.id.lv);
		et_id=(EditText)getView().findViewById(R.id.et_id);
		btn_clearCard=(Button) getView().findViewById(R.id.btn_clearCard);

		et_id.requestFocus();
		et_id.addTextChangedListener(watcher);
		btn_clearCard.setOnClickListener(this);

		mDSKernel = DSKernel.newInstance();//副屏初始化
		taskId = SharedPreferencesUtil.getLong(getActivity(), WELCOME_IMG_ID);

		tv_amount=(TextView)getView().findViewById(R.id.tv_amount);
		if(!Constatus.URGENT_TYPE){
			tv_amount.setText("人次：" + amount);
			wucanAdapter = new WucanAdapter(getActivity(), infolist);
			lv.setAdapter(wucanAdapter);
		}else{
			//紧急情况下
			getlunchNum();
		}

	}

	/**计算午餐人数*/
	private void getlunchNum(){
		long sysTime=System.currentTimeMillis();
		String date= SysTimeManage.getInstage().getDate(sysTime);
		lunchNum = where("date = ? and type=?", date,"1").count(SettletmentBean.class);
		tv_amount.setText("人次：" + lunchNum);
		selist=new ArrayList<>();
		uWAdapter=new UrgentWucanAdapter(getActivity(),selist);
		lv.setAdapter(uWAdapter);
	}

	@Override
	public void onStart() {
		super.onStart();
		et_id.setText("");
		et_id.requestFocus();
	}

	private  void Dingdan(String str) {

		synchronized(str){
			et_id.setText("");
			if(str.equals(on_card) &&
					((System.currentTimeMillis()-nonce_time))<=750){
				SoundPoolManage.getInstance(getActivity()).soundpPlay(2);
				toastUtil.Short(getActivity(),"  "+"刷卡频率过高")
						.setToastBackground(Color.WHITE,0).show();
				return;
			}
			on_card=str;
			nonce_time=System.currentTimeMillis();

		if(NetWorkUtil.isNetwork(getActivity())==false)
		{
			toastUtil.Short(getActivity(),"  "+"当前网络不可用")
					.setToastBackground(Color.WHITE,0).show();
			et_id.setText("");
			return;
		}
		items = new ArrayList<>();
		sm = new ArrayList<>();
		if (httptools == null) {
			httptools = new HttpTools(getActivity());
		}
		String cardId = str.substring(0, str.length());
		httptools.lunchPay(token, cardId,new JsonDingdan());
	}
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()){
			case R.id.btn_clearCard:
				et_id.setText("");
				et_id.requestFocus();
				break;
		}
	}

	public class JsonDingdan extends JsonHttpResponseHandler {
		@Override
		public void onSuccess(int statusCode, Header[] headers,
							  JSONObject response) {
			super.onSuccess(statusCode, headers, response);
			try {
				boolean code = response.getBoolean("code");
				String msg = response.getString("msg");
				if (code == true) {
					SoundPoolManage.getInstance(getActivity()).soundpPlay(1);
					JSONObject object = response.getJSONObject("data");
					String name = object.getString("name");
					String num = object.getString("num");
					String total = object.getString("total");
					String balance = object.getString("balance");
					infolist.add(0, new WucanEntity(name, num, total));
					toastUtil.Short(getActivity(), "  " + msg).setToastBackground(Color.WHITE, 0).show();
					amount = amount + 1;
					tv_amount.setText("人次：" + amount);
					ShowBalance(-1, balance,name);
					if (infolist.size() > 31) {
						infolist.remove(31);
					}
					wucanAdapter.notifyDataSetChanged();
					Utility.setListViewHeightBasedOnChildren(lv);
				} else {
					SoundPoolManage.getInstance(getActivity()).soundpPlay(2);
					toastUtil.Short(getActivity(), "  " + msg).setToastBackground(Color.WHITE, 0).show();
					int data = response.getInt("data");
					//付款码无效
					if (data == 0) {
						et_id.setText("");
					} else if (data == 2) { //余额不足
						ShowBalance(2,null, null);
					}
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}

		}

		@Override
		public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable e) {
			super.onFailure(statusCode, headers, responseBody, e);
			SoundPoolManage.getInstance(getActivity()).soundpPlay(2);
			toastUtil.Short(getActivity(), "  " + "请求失败，请重刷")
					.setToastBackground(Color.WHITE, 0).show();
		}
	}


	private TextWatcher  watcher  = new  TextWatcher() {
	    
	    @Override
	    public void onTextChanged(CharSequence s, int start, int before, int count) {
	    }
	    
	    @Override
	    public void beforeTextChanged(CharSequence s, int start, int count,
	            int after) {
	    }
	    
	    @Override
	    public synchronized void afterTextChanged(Editable s) {

			if (et_id.getText().length() == 8) {
				String card= et_id.getText().toString().trim();
				if(!Constatus.URGENT_TYPE){
					Dingdan(card);
				}else{
					addSqlit(card);
				}
			}
	    }
	};

	private void addSqlit(String card){
		synchronized(card){
			et_id.setText("");
			int cardnub=DataSupport.where("no = ?",card).count(Card.class);
			if(cardnub<1){
				et_id.setText("");
				SoundPoolManage.getInstance(getActivity()).soundpPlay(2);
				ShowBalance(11,"","支付失败");
				Toast.makeText(getActivity(),"刷卡频率过快或付款码无效",Toast.LENGTH_SHORT).show();
				return;
			}

			long sysTime=System.currentTimeMillis();
			String date=SysTimeManage.getInstage().getDate(sysTime);

			int num= DataSupport.where("card = ? and type = ? and date=?" ,card,"1",date )
					.count(SettletmentBean.class);
//			Log.e("lh", "num== "+num+"---card==="+card );
			if(num<=2){
				String id= SysTimeManage.getInstage().getOrderId(sysTime);
				int type=SysTimeManage.getInstage().getOrderType(sysTime);
				String time=SysTimeManage.getInstage().getDateTime(sysTime);
				SettletmentBean settl;
				if(num==0){
					settl=new SettletmentBean(id,card,1,"0",time,0,num+1,0,date,0);
				}else{
					settl=new SettletmentBean(id,card,1,"0",time,0,num+1,0,date,0);
				}
				boolean save= settl.save();
				if(save){
					lunchNum = lunchNum + 1;
					tv_amount.setText("人次：" + lunchNum);
					SoundPoolManage.getInstance(getActivity()).soundpPlay(1);
					Toast.makeText(getActivity(),"刷卡成功",Toast.LENGTH_SHORT).show();
					selist.add(0,settl);
					uWAdapter.notifyDataSetChanged();
					ShowBalance(11,"","刷卡成功");
				}else{
					SoundPoolManage.getInstance(getActivity()).soundpPlay(2);
					ShowBalance(11,"","支付失败");
					Toast.makeText(getActivity(),"刷卡失败",Toast.LENGTH_SHORT).show();
				}
			}else{
				SoundPoolManage.getInstance(getActivity()).soundpPlay(2);
				ShowBalance(11,"","支付失败");
				Toast.makeText(getActivity(),"您已支付满三次",Toast.LENGTH_SHORT).show();
			}
		}

	}

//
	private void ShowBalance(int type,String name,String balance){
		showBanlance(type,name,balance);
//		showHandle.postDelayed(mRunnable,1*1000);
	}
	int i=0;
	//显示余额
	private void showBanlance(int type,String title,String content){
		JSONObject json = new JSONObject();
		try {
			switch (type){
				case -1: //表示正常
					json.put("title", "余额：￥"+title);
					json.put("content",content+"  支付成功");
					break;
				case 2: //表示余额不足
					json.put("title", "支付失败");
					json.put("content","  余额不足");
					break;
				case 11: //表示离线状态下支付成功
					json.put("title", "");
					json.put("content",content);
					break;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		//显示文字
//		Log.e("lh","json---"+json.toString()+"==="+i);
		DataPacket packet = UPacketFactory.buildShowText(packageName,
				json.toString(),isendback);
		mDSKernel.sendData(packet);

	}
	private ISendCallback isendback=new ISendCallback() {
		@Override
		public void onSendSuccess(long taskId) {
//			onCheckFileExist();
			showHandle.postDelayed(mRunnable,1*1000);
		}

		@Override
		public void onSendFail(int errorId, String errorInfo) {
         //错误回调
		}

		@Override
		public void onSendProcess(long totle, long sended) {
			//发送状态回调
		}
	};

	private void onCheckFileExist(){
		//图片是否显示过监听
		mDSKernel.checkFileExist(taskId, new ICheckFileCallback() {
			@Override
			public void onCheckFail() {

			}

			@Override
			public void onResult(boolean exist) {
				//返回值为true是存在
				//返回值false是不存在
				if(exist){
					showImgWelcome(taskId);
				}else{
					fristShow();
				}
			}
		});
	}

	private void showImgWelcome(long taskId) {
		String json1 = UPacketFactory.createJson(DataModel.SHOW_IMG_WELCOME,"");
		mDSKernel.sendCMD(DSKernel.getDSDPackageName(),json1,taskId,null);
	}


	private void fristShow(){
		File file = new File(pathBig);
		if (!file.exists()) {
			Toast.makeText(getActivity(), "图片没有找到", Toast.LENGTH_SHORT).show();
			return;
		}
		taskId = mDSKernel.sendFile(DSKernel.getDSDPackageName(), pathBig, new ISendCallback() {
			@Override
			public void onSendSuccess(long l) {
				showImgWelcome(taskId);
				SharedPreferencesUtil.put(getActivity(), WELCOME_IMG_ID, taskId);
			}

			@Override
			public void onSendFail(int i, String s) {
			}

			@Override
			public void onSendProcess(long l, long l1) {
			}
		});
	}
	Runnable mRunnable=new Runnable() {
		@Override
		public void run() {
			onCheckFileExist();
		}
	};


//	private void showonFailureToast(){
//
//	}

//	private synchronized char pop(){
//		char card;
//
//		return card;
//	}


}
